package com.neutech.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class BookServlet extends HttpServlet {



    private static final List<Book> books = new ArrayList<>();
    public static class Book{
        String title;
        String author;
        String isbn;

        public Book(String title,String author,String isbn){
            this.title = title;
            this.author =author;
            this.isbn = isbn;
        }

        @Override
        public String toString() {
            return "Book{" +
                    "title='" + title + '\'' +
                    ", author='" + author + '\'' +
                    ", isbn='" + isbn + '\'' +
                    '}';
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path =req.getPathInfo();
        System.out.println(path);
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = req.getPathInfo();
        System.out.println(path);
        String title =req.getParameter("title");
        String author =req.getParameter("author");
        String isbn=req.getParameter("isbn");
        if("/addBook".equals(path)){
            boolean added = false;
            for (Book book:books){
                if (book.isbn.equals(isbn)){
                    resp.getWriter().println("ISBN已存在");
                    return;
                }
            }
            books.add(new Book(title,author,isbn));
            resp.getWriter().println("添加成功："+new Book(title,author,isbn));
        }else if("/deleteBook".equals(path)){
            books.removeIf(book -> book.isbn.equals(isbn));
            resp.getWriter().println("删除成功");
        }else {

        }

        String query =req.getParameter("query");
        if ("/searchBook".equals(path)){
            List<Book> results = new ArrayList<>();
            for (Book book:books){
                if (book.title.contains(query) || book.isbn.equals(query)){
                    results.add(book);
                }
            }
            if (results.isEmpty()){
                resp.getWriter().println("未找到图书");
            }else {
                for (Book book:results){
                    resp.getWriter().println(book);
                }
            }
        }else {

        }
    }


}
